package com.huwaiwai.nio.demo03;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * 如果两个通道中有一个是FileChannel
 * 可以直接将数据从一个channel传输到另外一个channel
 * Created by huweiwei on 2017/4/20.
 */
public class TransferFileChannel {

    public static void main(String [] args) throws IOException {
        RandomAccessFile in = new RandomAccessFile("C:\\test\\src\\main\\java\\com\\huwaiwai\\nio\\file\\nio-data.txt", "rw");
        FileChannel inChannel = in.getChannel();

        RandomAccessFile out = new RandomAccessFile("C:\\test\\src\\main\\java\\com\\huwaiwai\\nio\\file\\nio-out.txt", "rw");
        FileChannel outChannel = out.getChannel();

        long position = 0;
        long count = inChannel.size();

        //调用FileChannel的transferFrom或transferTo可以完成两个channel之间的传输
        outChannel.transferFrom(inChannel, position, count);
        inChannel.transferTo(position, count, outChannel);

        in.close();
        out.close();
    }
}
